<?php


namespace learn\middleware;


use app\models\user\UserToken;
use app\Request;
use learn\exceptions\AuthException;
use learn\interfaces\MiddlewareInterface;

/**
 * token验证
 * Class AuthTokenMiddleware
 * @package learn\middleware
 */
class AuthTokenMiddleware implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @param bool $force
     * @return mixed
     */
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $uid = null;
        $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
        if(!$token)  $token = trim(ltrim($request->header('Authorization'), 'Bearer'));
        try {
            $uid = UserToken::tokenDecode($token);
            if($uid == 0) return app('json')->make('2001', '用户登录信息过期');
        } catch (AuthException $e) {
            if ($force)
                return app('json')->make('2001', '用户登录信息过期');
        }
        Request::macro('isLogin', function () use (&$uid) {
            return !is_null($uid);
        });
        Request::macro('uid', function () use (&$uid) {
            return is_null($uid) ? 0 : $uid;
        });
        return $next($request);
    }
}